import { ref } from 'vue';

// 重试事件类型
export interface RetryEvent {
  type: 'request_retry_success' | 'request_retry_failed';
  requestId: string;
  url: string;
  data?: any;
  error?: any;
}

// 创建事件总线
class RetryEventBus {
  private listeners: Map<string, Function[]> = new Map();
  private retryEvents = ref<RetryEvent[]>([]);

  // 监听重试事件
  on(eventType: string, callback: Function) {
    if (!this.listeners.has(eventType)) {
      this.listeners.set(eventType, []);
    }
    this.listeners.get(eventType)!.push(callback);
  }

  // 移除监听器
  off(eventType: string, callback: Function) {
    const callbacks = this.listeners.get(eventType);
    if (callbacks) {
      const index = callbacks.indexOf(callback);
      if (index > -1) {
        callbacks.splice(index, 1);
      }
    }
  }

  // 触发事件
  emit(eventType: string, data: any) {
    const callbacks = this.listeners.get(eventType);
    if (callbacks) {
      callbacks.forEach((callback) => callback(data));
    }
  }

  // 添加重试事件
  addRetryEvent(event: RetryEvent) {
    this.retryEvents.value.push(event);
    this.emit(event.type, event);
  }

  // 获取重试事件
  getRetryEvents() {
    return this.retryEvents.value;
  }

  // 清空重试事件
  clearRetryEvents() {
    this.retryEvents.value = [];
  }
}

// 创建全局事件总线实例
export const retryEventBus = new RetryEventBus();

// 导出便捷方法
export const useRetryEventBus = () => {
  return {
    on: retryEventBus.on.bind(retryEventBus),
    off: retryEventBus.off.bind(retryEventBus),
    emit: retryEventBus.emit.bind(retryEventBus),
    addRetryEvent: retryEventBus.addRetryEvent.bind(retryEventBus),
    getRetryEvents: retryEventBus.getRetryEvents.bind(retryEventBus),
    clearRetryEvents: retryEventBus.clearRetryEvents.bind(retryEventBus),
  };
};
